<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "gky_qyh_dept_user".
 *
 * @property integer $id
 * @property string $dept_id
 * @property string $user_id
 * @property integer $qyh_id
 *
 * @property GkyQyhDepartment $dept
 * @property GkyQyhUser $user
 */
class GkyQyhDeptUser extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'gky_qyh_dept_user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['qyh_id'], 'integer'],
            [['dept_id','user_id'], 'string']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'dept_id' => 'Dept ID',
            'user_id' => 'User ID',
        ];
    }

    public function getDept(){

        return $this->hasOne(GkyQyhDepartment::className(),['id'=>'dept_id']);
    }

    public function getUser(){

        return $this->hasOne(GkyQyhUser::className(),['userid'=>'user_id']);
    }

    /**
     * 保存多条数据
     *
     * @param $departmentList
     */
    public static function saveList($corpid, $departmentList){
        $qyh = GkyQyh::findByCorpid($corpid);
        foreach($departmentList as $department){
            $deptUser = GkyQyhDeptUser::find()
                ->where([
                    'dept_id'=>$department['dept_id'],
                    'user_id'=>$department['user_id'],
                    'qyh_id' =>$qyh->id
                ])
                ->one();
            if($deptUser == null){
                $deptUser = new GkyQyhDeptUser();
                $deptUser->dept_id = $department['dept_id'];
                $deptUser->user_id = $department['user_id'];
                $deptUser->qyh_id = $qyh->id;
                $deptUser->save();
            }
        }
    }
}
